package control;

import entity.Image;
import entity.Product;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import utils.ServletUtil;

@WebServlet(name = "EditProductImage", urlPatterns = {"/backend/EditProductImage"})
public class EditProductImage extends HttpServlet {
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Form
        boolean formSucces = false;
        boolean formSuccessDeleteImg = false;
        Map<String, FileItem> formFields;
        
        // JPA
        EntityManagerFactory fact = Persistence.createEntityManagerFactory("vh11i_jeePU");
        EntityManager em = fact.createEntityManager();
        
        // Beans
        Product product = null;
        
        try {
            // Zoek het product via id (staat in de querystring)
            long productId = ServletUtil.getLong(request.getParameter("product_id"), -1);
            product = em.find(Product.class, productId);
            
            if (product != null) {
                request.setAttribute("product", product);
                
                if (request.getMethod().equals("POST")) {
                    formFields = ServletUtil.parseMultipartRequest(request);
                    
                    // Bekijk welke button is ingedrukt
                    if (formFields.containsKey("saveImgSubmit")) {
                        
                        if (product.getImage() == null) {
                            product.setImage(new Image());
                        }
                        
                        Image img = product.getImage();
                        img.setImage(formFields.get("image").get());
                        img.setMimeType(formFields.get("image").getContentType());
                        
                        if (img.getImage().length > 0) {
                            em.getTransaction().begin();
                            em.persist(product);
                            em.getTransaction().commit();
                            formSucces = true;
                        }
                    }
                    else if (formFields.containsKey("deleteImgSubmit")) {
                        
                        Image i = product.getImage();
                        product.setImage(null);
                        
                        em.getTransaction().begin();
                        em.remove(i);
                        em.persist(product);
                        em.getTransaction().commit();
                        formSucces = true;
                    }
                }
            }
        }
        finally {
            em.close();
            fact.close(); 
        }
        
        if (formSucces) {
            response.sendRedirect("EditProductImage?success=true&category_id=" + product.getCategory().getId());
        }
        //else if (formSuccessDeleteImg) {
        //    response.sendRedirect("EditProductImage?product_id=" + product.getId() + "&category_id=" + product.getCategory().getId());
        //}
        else {
            RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/editProductImage.jsp");
            dispatcher.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
